package com.study.lihan.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: lihan
 * @Date : 2022/1/12- 01
 * @DESCRIPTION: com.study.lihan.io
 * @version: 1.0
 */
public class SocketMultiplexSingleThread {
    private ServerSocketChannel server ;
    private Selector selector ;
    int port =9090;
    public static void main(String[] args) {

        SocketMultiplexSingleThread server = new SocketMultiplexSingleThread();
        server.start();
    }
    public void initServer(){
        try {
            server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress(port));
            selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        initServer();
        System.out.println("服务器启动了。。。。");
        try {
            while (true){
                while (selector.select(0)>0){//询问内核有没有事件
                    Set<SelectionKey> selectionKeys = selector.selectedKeys(); ///从多路复用器，取出有效key
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isAcceptable()){
                            acceptHandler(key);
                        }else if(key.isReadable()) {
                            readHanlder(key);
                        }
                    }


                };

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void acceptHandler(SelectionKey key){

        try {
            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
            SocketChannel client = channel.accept();
            client.configureBlocking(false);
            ByteBuffer buffer = ByteBuffer.allocate(81920);
            client.register(selector,SelectionKey.OP_READ,buffer);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>");
            System.out.println("新客户端："+ client.getRemoteAddress());
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>");


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readHanlder(SelectionKey key){

            SocketChannel client = (SocketChannel) key.channel();
            ByteBuffer buffer = (ByteBuffer) key.attachment();

            buffer.clear();
            int read =0;
        try {
            while (true){
                System.out.println("一直循环");
                read = client.read(buffer);
//如果客户端突然断开连接，返回- 1
                if(read > 0){
                    buffer.flip();
                    while (buffer.hasRemaining()){
                        client.write(buffer);
                    }
                    buffer.clear();
                }else if(read ==0){
                    break;
                }else {// -1 ,客户端关闭，isread（）一直为真
                    client.close();
                    break;
                }
                System.out.println("cccc啥时候疯狂触发");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
